﻿// See https://aka.ms/new-console-template for more information

using OpenAI;

var openAI = new OpenAI_DotNet();

var result = openAI.CreateChat().Result;
Console.WriteLine(result);



static async Task Main()
{
    string apiKey = "YOUR_API_KEY";
    string endpoint = "https://api.openai.com/v1/engines/text-davinci-003/completions";

    // 初始化对话上下文
    List<string> conversationHistory = new List<string>();

    while (true)
    {
        // 用户输入
        Console.Write("User: ");
        string userInput = Console.ReadLine();

        // 将用户输入添加到对话历史
        conversationHistory.Add($"User: {userInput}");

        // 构建输入，包含整个对话历史
        string inputText = string.Join("\n", conversationHistory);

        // 发送请求给OpenAI API
        string reply = await GetOpenAIReply(apiKey, endpoint, inputText);

        // 将回复添加到对话历史
        conversationHistory.Add($"AI: {reply}");

        // 输出生成的回复
        Console.WriteLine($"AI: {reply}");
    }
}

static async Task<string> GetOpenAIReply(string apiKey, string endpoint, string inputText)
{
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

        // 构建请求数据
        string requestBody = $"{{\"prompt\": \"{inputText}\", \"max_tokens\": 100}}";

        // 发送POST请求
        HttpResponseMessage response = await client.PostAsync(endpoint, new StringContent(requestBody));

        // 处理响应
        if (response.IsSuccessStatusCode)
        {
            string result = await response.Content.ReadAsStringAsync();
            // 解析生成的回复
            // 这里需要根据实际返回的 JSON 数据结构进行解析
            // 示例中使用简单的字符串提取，实际中可能需要更复杂的逻辑
            int startIndex = result.IndexOf("\"choices\":[{") + 13;
            int endIndex = result.IndexOf("\"}],", startIndex);
            string reply = result.Substring(startIndex, endIndex - startIndex);
            return reply;
        }
        else
        {
            Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
            return "Error";
        }
    }
}

